import express, { Request, Response } from "express";
import { v4 as uuid } from 'uuid'
import {
    addRecentlyService,
    delRecentlyService, recentlyEditService,
    recentlyListService,
    recentlyViewService
} from "../service/recentlyService";
import multer from "multer";
import path from "path";
import FileMethod from "../utils/fileMethod";
import file from "./file";
const router = express.Router()

// // 设置存储配置
// const storage = multer.diskStorage({
//     destination: function (req, file, cb) {
//         cb(null, path.resolve(__dirname, `../public/recently`)) // 确保这个文件夹已经存在
//     },
//     filename: function (req, file, cb) {
//         const suffix = file.originalname.split('.')[file.originalname.split('.').length - 1]
//         cb(null, `${uuid()}.${suffix}`)
//     }
// })
//
// const upload = multer({ storage: storage });
const storageEdit = multer.diskStorage({
    destination: function (req, file, cb) {
        console.log(file.originalname)
        cb(null, path.resolve(__dirname, `../public/recently`)) // 确保这个文件夹已经存在
    },
    filename: function (req, file, cb) {
        cb(null, `${file.originalname}`)
    }
})
const uploadEdit = multer({ storage: storageEdit });

router.post('/list',  async (req: Request, res: Response) => {
    const { name } = req.body
    await recentlyListService(res, req.headers[process.env.NODE_MANAGE_TOKEN as string] as string, name)
})


router.post('/del',  async (req: Request, res: Response) => {
    const { data } = req.body
    await delRecentlyService(res, JSON.parse(data))
})

router.post('/del/file',  async (req: Request, res: Response) => {
    const { fileURL } = req.body
    await FileMethod.fileDel(fileURL)
    res.send({ code: 200, message: '删除成功', data: null })
})

router.post('/add', async (req: Request, res: Response) => {
    const { name, describe, fileURL } = req.body
    await addRecentlyService(res, req.headers[process.env.NODE_MANAGE_TOKEN as string] as string, name, describe, fileURL)
})

router.post('/edit', uploadEdit.single('file'), async (req: Request, res: Response) => {
    const { name, describe, path } = req.body
    await recentlyEditService(res, name, describe, path)
})

router.post('/view',  async (req: Request, res: Response) => {
    const { path } = req.body
    await recentlyViewService(res, path)
})

export default router